package test

import (
	"fmt"
	"golang.org/x/net/websocket"
	"log"
	"net/http"
	"strings"
)

func echoHandler(ws *websocket.Conn) {
	msg := make([]byte, 512)
	defer func() {
		if err := recover(); err != nil {
			fmt.Println(err) //这里的err其实就是panic传入的内容，55
		}
	}()
	for {
		n, err := ws.Read(msg)
		if err != nil {
			log.Println(err.Error())
			return
		}
		fmt.Printf("Receive: %s\n", msg[:n])

		send_msg := "[" + string(msg[:n]) + "]"
		m, err := ws.Write([]byte(send_msg))
		if err != nil {
			log.Println(err.Error())
			return
		}
		fmt.Printf("Send: %s\n", msg[:m])
	}
}

var staticfs = http.FileServer(http.Dir("E:\\"))

//这里可以自行定义安全策略
func static(w http.ResponseWriter, r *http.Request) {
	//fmt.Printf("访问静态文件:%s\n", r.URL.Path)
	old := r.URL.Path
	r.URL.Path = strings.Replace(old, "/file/", "", 1)
	staticfs.ServeHTTP(w, r)
}

func main() {
	defer func() {
		if err := recover(); err != nil {
			fmt.Println(err) //这里的err其实就是panic传入的内容，55
		}
	}()

	http.Handle("/echo", websocket.Handler(echoHandler))
	http.HandleFunc("/file/", static)

	err := http.ListenAndServe("localhost:8080", nil)

	if err != nil {
		panic("ListenAndServe: " + err.Error())
	}
}
